<template>
	<div class="content">
		<el-upload class="avatar-uploader" 
		:action="upload" 
		:data='dataObj' 
		:show-file-list="false" 
		:on-success="handleAvatarSuccess"
		:multiple='false'
		:before-upload="beforeAvatarUpload"> 
		<img v-if="imageUrl" :src="imageUrl" class="avatar">
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
		</el-upload>
	</div>
</template>

<script>
	import {getUUID} from '../../config/UUID.js'
	export default {
		name: 'upload',
		props: {
		  value: String
		},
		data() {
			return {
				upload: 'http://newchart.oss-cn-beijing.aliyuncs.com',
				imageUrl:'',
				// imageUrl: '',
				dataObj: {
					policy: '',
					signature: '',
					key: '',
					ossaccessKeyId: '',
					dir: '',
					host: ''
				},
			}
		},
		// computed:{
		// 	imageUrl(){
		// 		return this.value
		// 	},
		// 	imageUrl: {
		// 		get: function () {
		// 		  return this.value
		// 		},
		// 		set: function (newValue) {
		// 		}
		// 	}
		// },
		
		methods: {
			handleAvatarSuccess(res, file) {
				this.imageUrl = this.dataObj.host + '/' + this.dataObj.key
				this.$emit('input', this.imageUrl)
				console.log(this.imageUrl)
			},
			beforeAvatarUpload(file) {
				return new Promise((resolve, reject) => {
						this.$axios.post('/api/oss/upload').then(res => {
							console.log(res)
							this.dataObj.policy = res.data.policy
							this.dataObj.signature = res.data.signature
							this.dataObj.ossaccessKeyId = res.data.accessid
							this.dataObj.key = res.data.dir +getUUID()+ file.name
							this.dataObj.dir = res.data.dir
							this.dataObj.host = res.data.host
							resolve(true)
						})
					})
				}
			}
		}
</script>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 78px;
		height: 78px;
		line-height: 78px;
		text-align: center;
	}

	.avatar {
		width: 78px;
		height: 78px;
		display: block;
	}
</style>
